package com.bobby.shop.web;

import com.bobby.shop.pojo.Article;
import com.bobby.shop.pojo.ArticleType;
import com.bobby.shop.pojo.User;
import com.bobby.shop.service.ArticleService;
import com.bobby.shop.service.ArticleTypeService;
import com.bobby.shop.service.UserService;
import com.bobby.shop.util.RandomCheckCode;
import com.bobby.shop.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.nio.ch.SelectorImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Date 2020/12/8 11:24
 * @Created wenjunpei
 */
@Controller
public class IndexController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleTypeService articleTypeService;

    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session) {
        ModelAndView mv = new ModelAndView();
        session.invalidate();
        mv.setViewName("redirect:/toLoginPage");
        return mv;
    }

    @GetMapping("/checkRegister")
    @ResponseBody
    public ServerResponse checkRegister(String loginName) {
        if(StringUtils.isEmpty(loginName)) {
            return ServerResponse.createBySuccess(false);
        }
        User user = userService.findByLoginName(loginName);
        if(user != null) {
            return ServerResponse.createBySuccess(false);
        }else {
            return ServerResponse.createBySuccess(true);
        }
    }

    @GetMapping("/searchContent")
    public ModelAndView searchContent(String content,
                                      @RequestParam(value = "type_code",required = true) String typeCode) {
        ModelAndView mv = new ModelAndView();
        List<Article> articleList = articleService.findByContentAndTypeCode(content,typeCode);
        List<ArticleType> articleTypeSmallList = articleTypeService.findArticleTypeByCode(typeCode);
        List<ArticleType> articleTypeBigList = articleTypeService.findAll();
        mv.setViewName("articleIndex");
        mv.addObject("articleList",articleList);
        mv.addObject("articleTypeSmallList",articleTypeSmallList);
        mv.addObject("articleTypeBigList",articleTypeBigList);
        return mv;
    }

    @GetMapping("/getCheckCode")
    public void getCheckCode(HttpServletRequest request,
                             HttpServletResponse response) {
        RandomCheckCode randomValidateCode = new RandomCheckCode();
        randomValidateCode.getRandomCode(request, response);//输出图片方法
    }

    @PostMapping("/register")
    public ModelAndView register(User user,String code,HttpSession session) {
        ModelAndView mv = new ModelAndView();
        String codeFromSession = (String) session.getAttribute(RandomCheckCode.RANDOMCODEKEY);
        session.removeAttribute(RandomCheckCode.RANDOMCODEKEY);
        if(StringUtils.isEmpty(code) || !code.equalsIgnoreCase(codeFromSession)) {
            mv.addObject("registerMsg","验证码错误");
            mv.setViewName("register");
            return mv;
        }
        user.setRole(1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            user.setCreateDate(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setDisabled(true);
        User userFromDB = userService.findByLoginName(user.getLoginName());
        if(userFromDB != null) {
            mv.addObject("registerMsg","用户名已存在");
            mv.setViewName("register");
            return mv;
        }
        userService.saveUser(user);
        mv.setViewName("redirect:/toLoginPage");
        return mv;
    }

    @RequestMapping("/toRegisterPage")
    public ModelAndView forwardToRegisterPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("register");
        return mv;
    }


    @RequestMapping("/toArticleInfoPage")
    public ModelAndView forwardToArticleInfoPage(@RequestParam("articleId") String articleId) {
        Article article = articleService.findByArticleId(articleId);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("articleInfo");
        mv.addObject("article",article);
        return mv;
    }

    @PostMapping("/login")
    public ModelAndView login(@RequestParam(value = "loginName") String loginName,
                              @RequestParam(value = "password") String password,
                              HttpSession session) {
        ModelAndView mv = new ModelAndView();
        User user = userService.findByLoginName(loginName);
        if(user == null || !user.getPassword().equals(password)) {
            mv.addObject("loginMsg","对不起,用户名或者密码错误!");
            mv.setViewName("login");
        }else {
            session.setAttribute("user",user);
            mv.setViewName("redirect:getArticleType");
        }
        return mv;
    }

    /*
     * @Description 转发到web-inf下的login页面
     * @param
     * @return org.springframework.web.servlet.ModelAndView
     * @date 2020/12/10 15:30
     * @auther wenjunpei
     */
    @RequestMapping("/toLoginPage")
    public ModelAndView forwardToLoginPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("login");
        return mv;
    }


    @RequestMapping("/getArticleType")
    public ModelAndView getArticleType(@RequestParam(value = "type_code",required = false)String typeCode) {
        if(StringUtils.isEmpty(typeCode)) {
            typeCode = "0001";
        }
        List<Article> articleList = articleService.findByTypeCode(typeCode);
        List<ArticleType> articleTypeSmallList = articleTypeService.findArticleTypeByCode(typeCode);
        List<ArticleType> articleTypeBigList = articleTypeService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("articleIndex");
        mv.addObject("articleList",articleList);
        mv.addObject("articleTypeSmallList",articleTypeSmallList);
        mv.addObject("articleTypeBigList",articleTypeBigList);
        return mv;
    }
}
